/**
 * 教育背景
 */
import React from 'react';
import { InputItem, Toast, Modal } from 'antd-mobile';
import { Spin } from 'antd';
import { router, withRouter } from 'umi';
import { createForm } from 'rc-form';
import { useRequest, defaultFormatResult } from '@/hooks';
import { dictionaryList } from '@/services/dictionary';
import { PageWrap, EditListItem, Button, Picker, DateRangePicker } from './components';
import { useFormChange } from '../hooks';
import { getEducationDetail, updateEducation, addEducation, deleteEducation } from '../service';

const Education = ({ location, form }) => {
    const { query } = location;
    const { nid: id } = query;
    const { getFieldProps } = form;

    const { hasFormChange, initialForm } = useFormChange(form);

    // 获取表单字典
    const { data: dictObj } = useRequest(
        () =>
            dictionaryList({
                codes: ['agreeType', 'academicYear']
            }),
        {
            formatResult: res => {
                if (res) {
                    const { code, data } = res;
                    if (code === 10000) {
                        const obj = {};
                        data.forEach(item => {
                            const { dictName, dictValue } = item;
                            const o = {
                                ...item,
                                label: dictName,
                                value: dictValue
                            };
                            if (obj[item.code]) {
                                obj[item.code].push(o);
                            } else {
                                obj[item.code] = [o];
                            }
                        });
                        return obj;
                    }
                }
                return undefined;
            }
        }
    );

    const { data, loading, run: fetchDetail } = useRequest(getEducationDetail, {
        manual: true,
        ...defaultFormatResult,
        onSuccess: () => {
            initialForm();
        }
    });

    const handleSubmit = flag => {
        form.validateFields(async (err, values) => {
            // console.log('handleSubmit -> values', values);
            if (!err) {
                const { rangeDate, academicYear, degree, ...rest } = values;
                const params = {
                    ...rest,
                    academicYear: academicYear?.[0] || '',
                    degree: degree?.[0] || '',
                    startTime: rangeDate?.[0] || '',
                    endTime: rangeDate?.[1] || ''
                };

                // console.log(params);
                // console.log(JSON.stringify(params));
                Toast.loading('提交中...', 5000);
                if (query?.nid) {
                    params.id = query?.nid;
                    updateEducation(params)
                        .then(res => {
                            const { code, msg } = res;
                            if (code === 10000) {
                                // Toast.info('操作成功');
                                history.goBack();
                            } else {
                                Toast.info(msg);
                            }
                        })
                        .finally(() => {
                            Toast.hide();
                        });
                } else {
                    params.talentCode = query?.talentCode;
                    addEducation(params)
                        .then(res => {
                            const { code, msg } = res;
                            if (code === 10000) {
                                // Toast.info('操作成功');
                                if (flag) {
                                    form.resetFields();
                                } else {
                                    history.goBack();
                                }
                            } else {
                                Toast.info(msg);
                            }
                        })
                        .finally(() => {
                            Toast.hide();
                        });
                }
            } else {
                const tempList = Object.values(err);
                if (tempList && tempList.length > 0) {
                    const { errors } = tempList[0];
                    Toast.info(errors[0]?.message);
                }
            }
        });
    };

    const handleDelete = () => {
        if (!id) {
            return;
        }
        Toast.loading('提交中...', 5000);
        deleteEducation(id)
            .then(res => {
                const { code, msg } = res;
                if (code === 10000) {
                    Toast.info('操作成功');
                    history.goBack();
                } else {
                    Toast.info(msg);
                }
            })
            .finally(() => {
                Toast.hide();
            });
    };

    const handleCheckDelete = () => {
        Modal.alert('确定删除此内容？', '', [
            { text: '取消' },
            {
                text: '确定',
                onPress: () => {
                    handleDelete();
                }
            }
        ]);
    };

    React.useEffect(() => {
        if (id) {
            fetchDetail(id);
        } else {
            initialForm();
        }
    }, [id]);

    const handleLeftClick = () => {
        if (hasFormChange()) {
            Modal.alert('存在未保存的内容，确定退出吗？', '', [
                { text: '取消' },
                {
                    text: '确定',
                    onPress: () => {
                        history.goBack();
                    }
                }
            ]);
        } else {
            history.goBack();
        }
    };

    return (
        <PageWrap
            title="教育背景"
            navbarProps={{ onLeftClick: handleLeftClick }}
            footer={
                query?.talentCode ? (
                    <>
                        <Button style={{ marginRight: 15, flex: 1 }} onClick={() => handleSubmit(true)}>
                            保存并继续添加
                        </Button>
                        <Button type="primary" style={{ flex: 1 }} onClick={handleSubmit}>
                            保存
                        </Button>
                    </>
                ) : (
                    <>
                        <Button style={{ marginRight: 15, flex: 1 }} onClick={handleCheckDelete}>
                            删除
                        </Button>
                        <Button type="primary" style={{ flex: 1 }} onClick={handleSubmit}>
                            完成
                        </Button>{' '}
                    </>
                )
            }
        >
            <div style={{ padding: '0 16px' }}>
                <Spin spinning={loading}>
                    <EditListItem title="起止时间">
                        <DateRangePicker
                            {...getFieldProps('rangeDate', {
                                initialValue:
                                    data?.startTime || data?.endTime ? [data?.startTime, data?.endTime] : undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择起止时间'
                                    }
                                ]
                            })}
                        >
                            请选择
                        </DateRangePicker>
                    </EditListItem>
                    <EditListItem title="学校" showArrow={false}>
                        <InputItem
                            {...getFieldProps('graduateSchool', {
                                initialValue: data?.graduateSchool || '',
                                rules: [{ required: true, message: '请输入学校' }]
                            })}
                            clear
                            placeholder="请输入"
                            maxLength={100}
                        />
                    </EditListItem>
                    <EditListItem title="专业" showArrow={false}>
                        <InputItem
                            {...getFieldProps('major', {
                                initialValue: data?.major || '',
                                rules: [{ required: true, message: '请输入专业' }]
                            })}
                            clear
                            placeholder="请输入"
                            maxLength={100}
                        />
                    </EditListItem>
                    <Picker
                        title="学历"
                        data={dictObj?.agreeType.filter(v => v.remark !== '1') || []}
                        {...getFieldProps('degree', {
                            initialValue: data?.degree ? [data?.degree] : undefined,
                            rules: [{ required: true, message: '请选择学历' }]
                        })}
                    >
                        <EditListItem title="学历">请选择</EditListItem>
                    </Picker>
                    <Picker
                        title="学制"
                        data={dictObj?.academicYear || []}
                        {...getFieldProps('academicYear', {
                            initialValue: data?.academicYear ? [data?.academicYear] : undefined,
                            rules: [{ required: true, message: '请选择学制' }]
                        })}
                    >
                        <EditListItem title="学制">请选择</EditListItem>
                    </Picker>
                </Spin>
            </div>
        </PageWrap>
    );
};

export default withRouter(createForm()(Education));
